'use strict'

const Service = require('egg').Service;

class MessagesService extends Service {

    async getMessageByGroup(group) {
        const { ctx, app } = this;
        let messageArr = await ctx.model.Messages.find({ group });
        return messageArr;
    }

    async getMessageByUserid(userid) {
        const { ctx, app } = this;
        const messageArr = await ctx.model.Messages.find({ userid }).sort({'_id': -1});
        const { username } = await ctx.model.Users.findOne({ userid });
        const list = messageArr.map(item => {
            const { messageId, messageTs, messageType, title, content, group, replyId, userid} = item;
            const newItem = {messageId, messageTs, messageType, title, content, group, replyId, userid, username }
            return newItem;
        })
        return list;
    }

    async getMessageByReply(userid) {
        const { ctx, app } = this;
        const messageArr = await ctx.model.Messages.find({ userid }).sort({'_id': -1});
        const replyArr = [];
        for (let i = 0; i < messageArr.length; i++) {
            const { replyId } = messageArr[i];
            if (replyId) {
                const message = await ctx.model.Messages.findOne({ messageId: replyId }).sort({'_id': -1});
                replyArr.push(message);
            }
        }
        return replyArr;
    }

    async newMessage(messageType, message) {
        const { ctx, app } = this;
        if (messageType === 'reply') {
            const { messageId, replyId } = message;
            let messageArr = await ctx.model.Messages.find({ messageId: replyId });
            if (messageArr.length === 1) {
                let mess = messageArr[0];
                let messId = mess.messageId;
                mess['replyId'] = messageId;
                await ctx.model.Messages.updateOne({ messageId: messId }, mess, err => {
                    if (err) return false;
                })
                
            } else {
                console.log("message have some key!");
            }
        }

        await ctx.model.Messages.create(message, err => {
            if (err) return false;
        });

        return true;
    }
}

module.exports = MessagesService;